﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper.DBContext;
using Guoc.BigMall.Application.Search;
using Guoc.BigMall.Application.ViewObject;
using Guoc.BigMall.Domain.Entity;
using Guoc.BigMall.Infrastructure;
using Guoc.BigMall.Infrastructure.Extension;
using Guoc.BigMall.Infrastructure.Log;

namespace Guoc.BigMall.Application.Facade
{
    public class DistributeMemberFacade : IDistributeMemberFacade
    {
        IDBContext _db;
        IContextFacade _context;
        ILogger _log;

        public DistributeMemberFacade(IDBContext db, IContextFacade context, ILogger log)
        {
            _db = db;
            _context = context;
            _log = log;
        }

        public IEnumerable<DistributeMemberVo> GetList(Pager page, SearchDistributeMember search)
        {
            dynamic param = new ExpandoObject();
            string where = "";
            
            if (search.Phone.NotNullOrEmpty())
            {
                where += " and  d.Phone = @Phone ";
                param.Phone = search.Phone;
            }

            if (search.MemberId.HasValue)
            {
                where += " and d.Path like @MemberId ";
                param.MemberId = string.Format("%#{0}#%", search.MemberId); ;
            }

            string sql = @"select d.Id, d.MemberId,d.Phone,d.CreatedOn,d.Path,d.ParentMemberId,m.RealName from distribute_member d 
inner join member m on d.MemberId = m.Id where 1=1 {0} Order By  d.Id desc LIMIT {1},{2}";
            sql = string.Format(sql, where, (page.PageIndex - 1) * page.PageSize, page.PageSize);
            var rows = _db.DataBase.Query<DistributeMemberVo>(sql, param);
            var sqlcount = string.Format(@" SELECT count(*) from distribute_member d inner join member m on d.MemberId = m.Id   WHERE 1=1 {0} ", where);
            page.Total = this._db.DataBase.ExecuteScalar<int>(sqlcount, param);

            return rows;
        }

        public void AddTopMember(int memberId)
        {
            var mbr = _db.Table<Member>().FirstOrDefault(n => n.Id == memberId);
            if (mbr == null)
            {
                throw new FriendlyException("会员不存在!");
            }
            if (_db.Table<DistributeMember>().Exists(n => n.MemberId == memberId))
            {
                throw new FriendlyException("会员已经是顶级分销员");
            }
            DistributeMember disMember = new DistributeMember()
            {
                Level = 1,
                MemberId = memberId,
                Path = "#" + memberId + "#",
                Phone = mbr.Phone,
                ParentMemberId = 0
            };

            _db.Insert(disMember);
            _db.SaveChange();

        }
    }
}
